﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Text;
using Cipyar.Core.DomainObjects;

namespace Cipyar.Core
{
    public class MailManager
    {
        public MailMessage CreateMailMessage(Settings settings, string[] attachmentFiles)
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(settings.MailSettings.FromAddress);
            mailMessage.Subject = settings.MailSettings.DefaultSubject;
            
            foreach (var to in settings.Recipients.To)
                mailMessage.To.Add(new MailAddress(to.Address));

            foreach (var cc in settings.Recipients.Cc)
                mailMessage.CC.Add(new MailAddress(cc.Address));

            foreach (var bcc in settings.Recipients.Bcc)
            {
                mailMessage.Bcc.Add(new MailAddress(bcc.Address));
            }

            AttachFiles(mailMessage, attachmentFiles);

            return mailMessage;
        }

        private void SendMail(MailMessage mailMessage, MailSettings mailSettings)
        {
            SmtpClient smtpClient = new SmtpClient();
            if (!string.IsNullOrEmpty(mailSettings.Username))
            {
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential(mailSettings.Username, mailSettings.Password);
            }
            smtpClient.Host = mailSettings.Smtp;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.EnableSsl = mailSettings.UseSsl;
            smtpClient.Port = int.Parse(mailSettings.Port);

            smtpClient.Send(mailMessage);
        }

        private void SendMail(FileManager fileManager, ConfigurationManager configurationManager)
        {
            MailMessage mailMessage = CreateMailMessage(configurationManager.Settings, fileManager.GetFiles());
            SendMail(mailMessage, configurationManager.Settings.MailSettings);
        }

        public void SendMail(string settingsFileName)
        {
            SendMail(new FileManager(settingsFileName), ConfigurationManager.GetConfigurationManager(settingsFileName));
        }

        public void SendMail()
        {
            SendMail(new FileManager(), ConfigurationManager.GetDefaultConfigurationManager());
        }

        private static void AttachFiles(MailMessage mailMessage, IEnumerable<string> files)
        {
            foreach (string file in files)
            {
                mailMessage.Attachments.Add(new Attachment(file));
            }
        }
    }
}
